package problem.year2022.Month12;

import java.util.HashMap;
import java.util.Map;

public class D1214 {

    public static void main(String[] args) {
        int ints = beautySum2("aabcb");
        System.out.println(ints);
    }

    public static int beautySum(String s) {
        char[] chars = s.toCharArray();
        int len = chars.length;
        int sum = 0;
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < len; i++) {
            int max = 1, min = 1;
            map.put(chars[i], 1);
            for (int j = i + 1; j < len; j++) {
                char key = chars[j];
                if (map.containsKey(key)) {
                    int val = map.get(key);
                    map.put(key, val + 1);
                } else {
                    map.put(key, 1);
                }
                max = Math.max(max, map.get(key));
                min = Math.min(min, map.get(key));
            }
            map.put(chars[i], map.get(chars[i]) - 1);
            sum += max - min;
        }
        return sum;
    }

    public static int beautySum2(String s) {
        int res = 0;
        for (int i = 0; i < s.length(); i++) {
            int[] cnt = new int[26];
            int maxFreq = 0;
            for (int j = i; j < s.length(); j++) {
                cnt[s.charAt(j) - 'a']++;
                maxFreq = Math.max(maxFreq, cnt[s.charAt(j) - 'a']);
                int minFreq = s.length();
                for (int k = 0; k < 26; k++) {
                    if (cnt[k] > 0) {
                        minFreq = Math.min(minFreq, cnt[k]);
                    }
                }
                res += maxFreq - minFreq;
            }
        }
        return res;
    }
}
